<template>
	<view class="content">
		<view class='index'>
			<!-- 固定搜索区域 -->
			<view class="search-container fixed-search">
				<view class="search-box">
					<image class="search-icon" src="/static/images/search.png"></image>
					<input class="search-input" type="text" v-model="searchKeyword" placeholder="搜索机构名称" @input="onSearchInput" @confirm="onSearchConfirm" />
					<text v-if="searchKeyword" class="clear-icon" @tap="clearSearch">×</text>
				</view>
				<view class="district-selector" @click="showDistrictPicker" hover-class="hover-effect">
					{{ selectedDistrict }} <text class="dropdown-icon">&#9662;</text>
				</view>
			</view>
			<!-- 顶部占位，与固定搜索区域高度一致 -->
			<view class="search-placeholder"></view>
			
			<!-- 地区选择器弹窗 -->
			<uni-popup ref="districtPopup" type="bottom">
				<view class="picker-container">
					<view class="picker-header">
						<text class="picker-cancel" @click="cancelDistrictSelect">取消</text>
						<text class="picker-title">选择地区</text>
						<text class="picker-confirm" :class="{'picker-confirm-disabled': isLoadingCities}" @click="confirmDistrictSelect">确定</text>
					</view>
					<view v-if="pickerLoading" class="picker-loading">
						<view class="loading-icon"></view>
						<text>加载中...</text>
					</view>
					<picker-view v-else class="picker-view" :value="tempSelectedIndex" @change="onPickerChange">
						<picker-view-column>
							<view class="picker-item" v-for="(item, index) in pickerData[0]" :key="'province-'+index">{{item}}</view>
						</picker-view-column>
						<picker-view-column>
							<view class="picker-item" v-for="(item, index) in pickerData[1]" :key="'city-'+index">
								<text v-if="index === 0 && isLoadingCities">{{loadingCityText}}</text>
								<text v-else>{{item}}</text>
							</view>
						</picker-view-column>
					</picker-view>
				</view>
			</uni-popup>
			
			<view class='commonLayout'>				  
				<view class='item' @click="goDetail(item.organId)" v-for="item in organList" :key="item.organId">
					<view class='flex-between'>
						<view class='item_title'>{{item.companyName}}</view>
						<view class='item_detail'>了解详情</view>
					</view>
					<view class='item_des'>
						<view class="tag">资质齐全</view>
						<view class="tag">正规机构</view>
					</view>
					<view class='flex-between company'>
						<image class="company_logo" :src="globalData.OSS_URL + item.mainImg" />
						<view class='company_info'>
							<view class='company_name text-ellipsis'>{{ item.companyAddr }}</view>
							<view class='company_location'>
								<image class="location-icon" src="/static/images/dingwei.png"></image>
								<text>{{ item.districtAncestors[0]['catName'] }} - {{ item.districtAncestors[1]['catName'] }}</text>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view v-if="loading" class="loading">
				<view class="loading-spinner"></view>
				<text>加载中...</text>
			</view>
    		<view v-if="noMoreData" class="no-more">没有更多数据了</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		onBeforeMount,
		computed,
		nextTick,
		onMounted,
		watch,
		onUnmounted
	} from 'vue';
	import api from '@/utils/api.js';
	import { globalData } from '@/utils/util';
	import { onReachBottom, onPullDownRefresh, onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app';
	import uniPopup from '@/uni_modules/uni-popup/components/uni-popup/uni-popup.vue';
	
	const organList = ref([])
	const curPage = ref(1)
	const loading = ref(false); // 是否正在加载
	const noMoreData = ref(false); // 是否没有更多数据
	const searchKeyword = ref(''); // 搜索关键词
	const districtPopup = ref(null); // 地区选择弹窗引用

	// 获取省市
	const selectedIndex = ref([0, 0]);
	const tempSelectedIndex = ref([0, 0]); // 临时选中索引，用于弹窗内选择
	const pickerData = ref([['全部'],['全部']])
	const pickerLoading = ref(false);
	let firstLevelData = []; // 省份数据
	let cityArr = []; // 城市数据
	const districtId = ref(''); // 城市id
	let scrollTimer = null; // 滚动定时器
	let currentProvinceIndex = 0; // 当前处理的省份索引
	const loadingCityText = ref('全部(加载中...)');
	
	// 城市数据缓存对象，key为省份catId，value为该省份下的城市数组
	const cityDataCache = reactive({});
	
	// 监听第一级选择变化，设置二级为加载中状态
	const isLoadingCities = ref(false);
	
	// 直辖市ID列表
	const directMunicipalitiesIds = [110000, 310000, 120000, 500000];
	
	// 判断是否为直辖市
	const isDirectMunicipality = (catId) => {
		return directMunicipalitiesIds.includes(catId);
	};
	
	// 选中的地区显示文本
	const selectedDistrict = computed(() => {
		if (pickerData.value[0].length <= 1) return '地区';
		
		const [provinceIndex, cityIndex] = selectedIndex.value;
		
		// 全部-全部的情况
		if (provinceIndex === 0 && cityIndex === 0) {
			return '全部';
		}
		
		// 只选省份的情况
		if (provinceIndex > 0 && cityIndex === 0) {
			return pickerData.value[0][provinceIndex];
		}
		
		// 省市都选的情况
		if (provinceIndex > 0 && cityIndex > 0 && 
			provinceIndex < pickerData.value[0].length && 
			cityIndex < pickerData.value[1].length) {
			return pickerData.value[0][provinceIndex] + ' - ' + pickerData.value[1][cityIndex];
		}
		
		return '地区';
	});
	
	onBeforeMount(() => {
		getProvince()
	})
	
	const getData = async () => {
		if (loading.value || noMoreData.value) return; // 防止重复加载和没有更多数据时继续请求
		loading.value = true; // 开始加载
		try {
		    await api.organInfoLst({
				"curPage": curPage.value,
				"pageSize": 20,
				districtId: districtId.value,
				companyName: searchKeyword.value // 添加搜索关键词参数
			}).then(res => {
				if (res.code === 0) {
					if(res.data.itemLst.length <= 0) {
						noMoreData.value = true; // 没有更多数据
						return;
					}
					res.data.itemLst.forEach(item => {
					    item.mainImg = item.mainImg ? item.mainImg.split(',')[0] : ''
					});
					organList.value = curPage.value === 1 ? res.data.itemLst : [...organList.value, ...res.data.itemLst];
				}
			})
		} catch (error) {
			console.log(error);
		} finally {
			loading.value = false; // 加载完成
		}
		return Promise.resolve(); // 返回Promise以支持链式调用
	}
	
	// 搜索输入事件
	const onSearchInput = (e) => {
		searchKeyword.value = e.detail.value;
	}
	
	// 清空搜索
	const clearSearch = () => {
		searchKeyword.value = '';
		resetSearch();
		getData();
	}
	
	// 搜索确认事件
	const onSearchConfirm = () => {
		resetSearch();
		getData();
	}
	
	// 重置搜索状态
	const resetSearch = () => {
		curPage.value = 1;
		noMoreData.value = false;
		organList.value = [];
	}
	
	onReachBottom(() => {
		curPage.value++
		getData();
    });

	const goDetail = (organId) => {
		uni.navigateTo({
			url: `/pages/institutionDetail/institutionDetail?organId=${organId}`
		})
	}

	// 显示地区选择器弹窗
	const showDistrictPicker = () => {
		tempSelectedIndex.value = [...selectedIndex.value]; // 复制当前选择作为临时值
		nextTick(() => {
			districtPopup.value.open('bottom');
		});
	}
	
	// 取消地区选择
	const cancelDistrictSelect = () => {
		districtPopup.value.close();
	}
	
	// 确认地区选择
	const confirmDistrictSelect = () => {
		// 如果城市数据正在加载中，不允许确认
		if (isLoadingCities.value) {
			uni.showToast({ title: '城市数据加载中，请稍候', icon: 'none' });
			return;
		}
		
		// 如果存在延时操作，立即清除
		if (scrollTimer) {
			clearTimeout(scrollTimer);
			scrollTimer = null;
		}
		
		// 更新选中的索引
		selectedIndex.value = [...tempSelectedIndex.value];
		
		// 根据选择确定districtId
		const [provinceIndex, cityIndex] = tempSelectedIndex.value;
		
		// 选择了"全部-全部"
		if (provinceIndex === 0) {
			districtId.value = ''; // 不限省份
		} 
		// 选择了特定省份，但城市选择了"全部"
		else if (cityIndex === 0) {
			// 确保firstLevelData不为空且索引有效
			if (firstLevelData.length > 0 && (provinceIndex - 1) < firstLevelData.length) {
				const selectedProvince = firstLevelData[provinceIndex - 1];
				districtId.value = selectedProvince.catId; // 使用省份ID
			} else {
				uni.showToast({ title: '无效的省份选择', icon: 'none' });
				return;
			}
		} 
		// 选择了特定省份和特定城市
		else if (cityArr && cityArr.length > 0 && (cityIndex - 1) < cityArr.length) {
			districtId.value = cityArr[cityIndex - 1].catId; // 使用城市ID
		} else {
			uni.showToast({ title: '请选择有效地区', icon: 'none' });
			return;
		}
		
		console.log(`已选择地区: ${selectedDistrict.value}, ID: ${districtId.value}`);
		
		// 关闭弹窗并重新加载数据
		districtPopup.value.close();
		resetSearch();
		getData();
	}
	
	// Picker内部值变化
	const onPickerChange = async (e) => {
		const values = e.detail.value;
		
		// 清除之前可能存在的延时操作
		if (scrollTimer) {
			clearTimeout(scrollTimer);
		}
		
		// 判断第一列是否变化
		if (values[0] !== tempSelectedIndex.value[0]) {
			// 记录当前正在处理的省份索引
			currentProvinceIndex = values[0];
			
			// 立即更新第一列索引
			tempSelectedIndex.value = [values[0], 0]; // 重要：始终重置第二列为0
			
			// 立即将第二列设为加载中状态
			isLoadingCities.value = true;
			loadingCityText.value = '全部(加载中...)';
			
			// 设置第二列只显示全部选项，表示加载中
			pickerData.value[1] = ['全部(加载中...)'];
			
			// 添加延时处理，防止频繁请求
			scrollTimer = setTimeout(async () => {
				// 检查当前处理的省份是否仍是用户选择的省份
				if (currentProvinceIndex !== tempSelectedIndex.value[0]) {
					console.log('省份已变化，取消加载');
					return; // 如果用户已经滚动到其他省份，取消当前加载
				}
				
				// 如果选择了"全部"省份，则不需要请求城市数据
				if (currentProvinceIndex === 0) {
					pickerData.value[1] = ['全部'];
					isLoadingCities.value = false;
					return;
				}
				
				// 否则请求选中省份的城市数据
				const selectedProvince = firstLevelData[currentProvinceIndex - 1]; // 因为添加了"全部"，所以索引-1
				
				if (!selectedProvince) {
					console.error('无效的省份索引', currentProvinceIndex);
					pickerData.value[1] = ['全部'];
					isLoadingCities.value = false;
					return;
				}
				
				const provinceCatId = selectedProvince.catId;
				
				// 检查是否是直辖市（北京、上海、天津、重庆）
				if (isDirectMunicipality(provinceCatId)) {
					console.log(`直辖市: ${selectedProvince.catName}，只显示全部选项`);
					cityArr = [];
					pickerData.value[1] = ['全部'];
					isLoadingCities.value = false;
					return;
				}
				
				// 再次检查是否仍是当前处理的省份
				if (currentProvinceIndex !== tempSelectedIndex.value[0]) {
					console.log('省份已变化，取消加载');
					return;
				}
				
				// 检查是否有缓存数据
				if (cityDataCache[provinceCatId]) {
					// 使用缓存数据
					console.log(`使用缓存的城市数据: ${selectedProvince.catName}`);
					cityArr = cityDataCache[provinceCatId];
					
					// 最后检查一次是否仍是当前处理的省份
					if (currentProvinceIndex !== tempSelectedIndex.value[0]) {
						console.log('省份已变化，取消更新UI');
						return;
					}
					
					// 城市数据添加"全部"选项
					pickerData.value[1] = ['全部', ...cityArr.map(item => item.catName)];
					isLoadingCities.value = false;
				} else {
					// 没有缓存，需要请求新数据
					console.log(`请求新的城市数据: ${selectedProvince.catName}`);
					pickerLoading.value = true;
					try {
						await api.districtChild({parentId: provinceCatId}).then(res => {
							// 最后检查一次是否仍是当前处理的省份
							if (currentProvinceIndex !== tempSelectedIndex.value[0]) {
								console.log('省份已变化，取消更新UI');
								return;
							}
							
							cityArr = res.data;
							// 缓存城市数据
							console.log(`缓存城市数据: ${selectedProvince.catName}, 城市数量: ${res.data.length}`);
							cityDataCache[provinceCatId] = cityArr;
							// 城市数据添加"全部"选项
							pickerData.value[1] = ['全部', ...cityArr.map(item => item.catName)];
						});
					} catch (error) {
						console.error(`加载城市失败: ${error}`);
						uni.showToast({ title: '加载城市失败', icon: 'none' });
						// 加载失败时，仍保持全部选项
						pickerData.value[1] = ['全部'];
					} finally {
						pickerLoading.value = false;
						isLoadingCities.value = false;
					}
				}
			}, 300); // 增加延时，减少频繁请求
		} else if (values[1] !== tempSelectedIndex.value[1]) {
			// 只有第二列变化，直接更新索引
			tempSelectedIndex.value[1] = values[1];
		}
	}
	
	const getProvince = async () => {
	    try {
			await api.districtFirst().then(res => {
				firstLevelData = res.data
				// 添加"全部"选项
				pickerData.value[0] = ['全部', ...res.data.map(item => item.catName)];
				getfirstProvince(firstLevelData)
			})
		} catch (error) {
			uni.showToast({ title: '加载省份失败', icon: 'none' });
	    }
	}
	
	// 初始化城市
	const getfirstProvince = async (firstLevelData) => {
		// 默认选择全部
		selectedIndex.value = [0, 0];
		tempSelectedIndex.value = [0, 0];
		districtId.value = '';
		getData();
		
		// 预加载第一个省份的城市数据
		if (firstLevelData.length > 0) {
			const firstProvinceCatId = firstLevelData[0].catId;
			
			// 判断是否为直辖市，如果是则不需要预加载城市数据
			if (isDirectMunicipality(firstProvinceCatId)) {
				console.log(`预加载跳过 - 直辖市: ${firstLevelData[0].catName}`);
				return;
			}
			
			try {
				await api.districtChild({parentId: firstProvinceCatId}).then(res => {
					cityArr = res.data;
					// 缓存第一个省份的城市数据
					cityDataCache[firstProvinceCatId] = cityArr;
				});
			} catch (error) {
				console.error('预加载城市数据失败', error);
			}
		}
	}

	onMounted(() => {
		// 初始化完成后可以添加额外的处理逻辑
		console.log('页面加载完成');
	});
	
	// 下拉刷新处理
	onPullDownRefresh(() => {
		resetSearch();
		getData().then(() => {
			uni.stopPullDownRefresh();
		});
	});
	
	// 清除所有缓存并重新获取数据
	const refreshAllData = () => {
		// 清空城市数据缓存
		Object.keys(cityDataCache).forEach(key => {
			delete cityDataCache[key];
		});
		console.log('已清空城市数据缓存');
		
		// 重新获取省份数据
		getProvince();
	};
	
	// 监听地区选择器的加载状态，在城市数据加载中时禁用确认按钮
	watch(isLoadingCities, (newVal) => {
		if (newVal) {
			console.log('城市数据加载中...');
		} else {
			console.log('城市数据加载完成');
		}
	});
	
	// 组件销毁时清除定时器
	onUnmounted(() => {
		if (scrollTimer) {
			clearTimeout(scrollTimer);
			scrollTimer = null;
		}
	});
	
	// 分享给朋友
	onShareAppMessage(() => {
		return {
			title: '飞手之家 - 专业的无人机服务平台',
			path: '/pages/index/index',
			imageUrl: '/static/images/head.jpg'
		};
	});
	
	// 分享到朋友圈
	onShareTimeline(() => {
		return {
			title: '飞手之家 - 专业的无人机服务平台',
			query: '', // 如果有参数可以带上
			imageUrl: '/static/images/head.jpg'
		};
	});
</script>

<style lang="scss" scoped>
	.index {
		font-size: 16px;
		background: #f5f7fa;
		min-height: 100vh;
	}
	
	.fixed-search {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		z-index: 100;
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
	}
	
	.search-placeholder {
		height: 100rpx; /* 与search-container高度一致 */
	}
	
	.search-container {
		display: flex;
		padding: 20rpx;
		background-color: #fff;
		align-items: center;
		height: 60rpx;
	}
	
	.search-box {
		flex: 1;
		display: flex;
		align-items: center;
		background-color: #f5f5f5;
		border-radius: 36rpx;
		padding: 10rpx 20rpx;
		margin-right: 20rpx;
	}
	
	.search-icon {
		width: 36rpx;
		height: 36rpx;
		margin-right: 10rpx;
	}
	
	.search-input {
		flex: 1;
		height: 60rpx;
		font-size: 28rpx;
	}
	
	.district-selector {
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		min-width: 150rpx;
		text-align: center;
		font-size: 28rpx;
		color: #333;
		background-color: #f5f5f5;
		padding: 10rpx 20rpx;
		border-radius: 36rpx;
	}
	
	.dropdown-icon {
		font-size: 24rpx;
		margin-left: 5rpx;
	}
	
	.picker-container {
		background-color: #fff;
		border-radius: 20rpx 20rpx 0 0;
	}
	
	.picker-header {
		display: flex;
		justify-content: space-between;
		padding: 30rpx;
		border-bottom: 1px solid #eee;
	}
	
	.picker-cancel {
		color: #999;
	}
	
	.picker-title {
		font-weight: bold;
	}
	
	.picker-confirm {
		color: #2cbaff;
	}
	
	.picker-confirm-disabled {
		color: #999 !important;
		opacity: 0.5;
	}
	
	.picker-view {
		height: 400rpx;
		width: 100%;
	}
	
	.picker-item {
		line-height: 80rpx;
		text-align: center;
		color: #333;
	}

	/* 加载中文本样式 */
	.picker-item text {
		color: inherit;
	}

	.item {
		background-color: #fff;
		border-radius: 12px;
		padding: 24px 20px;
		margin: 16px 0;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

		.item_title {
			font-size: 18px;
			font-weight: bold;
			padding-bottom: 16px;
			flex: 1;
			color: #333;
		}

		.item_detail {
			align-self: start;
			color: #2cbaff;
			background: rgba(44, 186, 255, 0.1);
			padding: 6px 12px;
			border-radius: 30px;
			font-size: 14px;
		}

		.item_des {
			display: flex;
			margin-bottom: 16px;
			
			.tag {
				background: rgba(44, 186, 255, 0.1);
				color: #2cbaff;
				padding: 4px 10px;
				margin-right: 12px;
				border-radius: 4px;
				font-size: 12px;
			}
		}

		.company {
			display: flex;
			align-items: center;
			padding-top: 16px;
			border-top: 1px solid #f0f0f0;
		}
		
		.company_logo {
			width: 60px;
			height: 60px;
			border-radius: 8px;
			object-fit: cover;
			margin-right: 16px;
			border: 1px solid #f0f0f0;
		}

		.company_info {
			flex: 1;
		}
		
		.company_name {
			font-size: 14px;
			color: #333;
			margin-bottom: 8px;
			line-height: 1.4;
		}
		
		.company_location {
			display: flex;
			align-items: center;
			font-size: 12px;
			color: #999;
			
			.location-icon {
				width: 16px;
				height: 16px;
				margin-right: 4px;
			}
		}
	}

	.text-ellipsis {
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
	}

	.loading {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 30rpx;
		color: #999;
		
		.loading-spinner {
			width: 40rpx;
			height: 40rpx;
			border: 3rpx solid rgba(44, 186, 255, 0.3);
			border-top: 3rpx solid #2cbaff;
			border-radius: 50%;
			margin-bottom: 10rpx;
			animation: spin 1s linear infinite;
		}
	}
	
	.no-more {
		text-align: center;
		padding: 30rpx;
		color: #999;
		font-size: 14px;
	}

	.clear-icon {
		font-size: 40rpx;
		color: #999;
		padding: 0 10rpx;
	}
	
	.hover-effect {
		opacity: 0.8;
	}
	
	.picker-loading {
		height: 400rpx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		color: #999;
	}
	
	.loading-icon {
		width: 60rpx;
		height: 60rpx;
		border: 4rpx solid #f3f3f3;
		border-top: 4rpx solid #2cbaff;
		border-radius: 50%;
		margin-bottom: 20rpx;
		animation: spin 1s linear infinite;
	}
	
	@keyframes spin {
		0% { transform: rotate(0deg); }
		100% { transform: rotate(360deg); }
	}

	/* 添加下拉刷新的动画效果 */
	.pull-refresh {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 80rpx;
		color: #2cbaff;
	}
</style>